﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Model.Framework;
using Newtonsoft.Json;

namespace WebApplication.Admin
{

    /// <summary>
    /// Handler 的摘要说明
    /// </summary>
    public class Handler : IHttpHandler
    {
        delegate void RequestHandler(HttpContext context);
        static Dictionary<string, RequestHandler> HandlerDict = new Dictionary<string, RequestHandler>();
        static BLL.Framework framework = new BLL.Framework();

        static Handler()
        {
            HandlerDict.Add("GetResources", Handler.GetResources);
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (HandlerDict.ContainsKey(context.Request["mode"]))
            {
                HandlerDict[context.Request["mode"]](context);
            }
            else
            {
                context.Response.Write(BasePage.InvalidParametersJsonText);
            }
        }

        private static void GetResources(HttpContext context)
        {
            var cachedGridRows = (from resource in framework.Resources select resource).ToList();

            var hierarchyRows = from resource in cachedGridRows
                                select new
                                {
                                    ID = resource.ID.ToString(),
                                    Name = resource.Name,
                                    Url = resource.Url,
                                    IconUrl = resource.IconUrl,
                                    ParentID = resource.PID.HasValue ? resource.PID.ToString() : "",
                                    Visible=resource.Visible.ToString(),
                                    tree_loaded = true,
                                    tree_parent = resource.PID.HasValue ? resource.PID.ToString() : "",
                                    tree_level = LoadAllRowsExpanded_GetRowLevel(resource.PID, cachedGridRows),
                                    tree_leaf = LoadAllRowsExpanded_IsLeafRow(resource.ID, cachedGridRows),
                                    tree_expanded = true
                                };
            var list = hierarchyRows.Where(x => x.tree_level == 0).ToList();
            var result = new List<object>();
            list.ForEach(x =>
            {
                result.Add(x);
                result.AddRange(hierarchyRows.Where(w => w.ParentID == x.ID).ToList());
            });

            context.Response.Write(JsonConvert.SerializeObject(new { page = 1, total = 1, records = result.Count(), rows = result, userdata = new object() }));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private static int LoadAllRowsExpanded_GetRowLevel(Guid? parentID, List<Resource> cachedGridRows)
        {
            int level = 0;
            while (parentID != null)
            {
                level++;
                var result = from r in cachedGridRows
                             where r.ID == parentID
                             select r;

                parentID = result.Single().PID;
            }

            return level;
        }

        private static bool LoadAllRowsExpanded_IsLeafRow(Guid? productID, List<Resource> cachedGridRows)
        {
            foreach (Resource retailData in cachedGridRows)
            {
                if (retailData.PID == productID)
                {
                    return false;
                }
            }

            return true;
        }
    }
}